package com.itheima.aop;

import com.itheima.Utils.JwtUtils;
import com.itheima.mapper.operateMapper;
import com.itheima.pojo.operateLog;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Map;

@Component
@Slf4j
//@Aspect
public class logAspect {
    @Autowired
    private operateMapper operateMapper;
    @Autowired
    private HttpServletRequest request;

    @Around("@annotation(com.itheima.anno.Mylog)")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        //1.获取当前操作时间
        LocalDateTime operateTime = LocalDateTime.now();
        //2.获取运行前时间
        long startTime = System.currentTimeMillis();
        //3.运行目标方法
        Object result = joinPoint.proceed();
        //4.获取运行后时间
        long endTime =  System.currentTimeMillis();
        //5.计算执行时间
        long coreTime = endTime - startTime;
        //6.获取操作人id
        String token = request.getHeader("token");
        //7.解析token
        Claims claims = JwtUtils.parseJWT(token);

        Integer id = (Integer) claims.get("id");

        //8.获取目标方法所在类类名
        String classname = joinPoint.getTarget().getClass().getName();
        //9.获取目标方法 方法名
        String methodName = joinPoint.getSignature().getName();
        //10.获取目标方法参数
        Object[] args = joinPoint.getArgs();
        String methodParams = Arrays.toString(args);
        String resultValue = result.toString();
        operateLog logInfo = new operateLog(null,id,operateTime,classname,methodName,methodParams,resultValue,coreTime,null);
        operateMapper.Inseartlog(logInfo);
        return result;
    }
}
